<template>
	<el-popover ref="popover" popper-class="mp-micro padding-no" :disabled="disabled" @hide="$emit('blur')" @show="$emit('show')" v-model="visible" trigger="click">
		<selectTree :data="deptList" ref="selectTree" class="popover-height" :checkStrictly="true" :value="valueShow" @node-expand="resetPosition" @handleCheckChange="handleCheckChange" @handleClickNode="handleClickNode" :defaultProps="defaultProps" :showCheckbox="isCheckbox">
			<template v-slot:top>
				<slot name="top"></slot>
			</template>
			<template v-slot="{ data }" v-if="isFilter">
				{{ data.name }}<br />
				<span class="prompt" :class="isCheckbox ? '' : 'radio'" v-if="data.name1">{{
					data.name1
				}}</span>
			</template>
		</selectTree>
		<inputContent style='height:auto' :disabled="disabled" :clear="clear" v-clickoutside="hideOnly" :visible="visible" :selected="value" slot="reference" v-bind="$attrs">
			<div style="margin-right:6px;" v-for="one in tagArr" :key="one.id">
				<departmentLabel @close="close(one)" :disableClose="disabled">{{one.name}}</departmentLabel>
			</div>
		</inputContent>
	</el-popover>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import inputContent from '@/afterSales/components/select/inputContent.vue';
import Clickoutside from 'element-ui/src/utils/clickoutside';
import selectTree from '@/afterSales/components/moSelect/selectTree.vue';
import Emitter from '@/afterSales/mixins/emitter';
import { CommonModule } from '@/store/modules/common'
// eslint-disable-next-line no-restricted-imports
import { keyBy } from 'lodash';
import departmentLabel from './departmentLabel.vue';
@Component({
  name: 'deptSelect',
  components: {
    inputContent,
    selectTree,
    departmentLabel
  },
  directives: {
    Clickoutside
  }
})
export default class extends Vue {
  @Prop(String) public fieldType!: any;
  @Prop({ type: [String, Number] }) public value!: string;
  @Prop({ default: false }) public disabled!: boolean;
  @Prop({ default: false }) public isCheckbox!: boolean;
  @Prop({ default: false }) public isService!: boolean;
  @Prop({ default: false }) public isFilter!: boolean;
  @Prop({ default: {} }) public selectMap!: any;
  @Prop({ default: () => (CommonModule as any).publicCache.departmentTree?.tree || [] }) private deptList!: any[];
  private visible = false;
  private popperElm: any;
  private get defaultProps () {
    if (this.isService) {
      return {
        children: 'children',
        label: 'name',
        value: 'id'
      }
    } else {
      return {
        children: 'children',
        label: 'name',
        value: '_id'
      };
    }
  }

  private get tagArr () {
    if (this.value) {
      return this.value.split(',').map((id) => {
        return this.selectMap[id] || {};
      });
    }
    return [];
  }

  private get valueShow () {
    if (!this.value) {
      return this.isCheckbox ? [] : '';
    }
    if (this.isCheckbox) {
      return this.value
        .split(',');
    }
    return this.value;
  }

  public focus () {
    this.visible = true;
  }

  public hideOnly () {
    this.visible = false;
  }

  private resetPosition () {
    this.$nextTick(() => {
      const popover = this.$refs.popover as any;
      const sheetTree1 = this.$refs.selectTree as selectTree;
      if (sheetTree1 && popover) {
        setTimeout(() => {
          popover.updatePopper();
        }, 100);
      }
    });
  }

  private handleCheckChange (options) {
    this.$emit('input', options.join(','));
    this.change();
  }

  private change (v = '') {
    this.$emit('on-change');
    Emitter.methods.dispatch.call(this, 'ElFormItem', 'el.form.change', v);
  }

  private handleClickNode (id) {
    if (id) {
      this.$emit('input', id);
    } else {
      this.$emit('input', '');
    }
    this.change();
  }

  private close (item) {
    const clearId = (item._id || item.id) + '';
    const valueArr = this.value.split(',');
    const value = valueArr.filter((id) => id !== clearId).join(',');
    this.$emit('input', value);
    this.change();
  }

  private clear () {
    this.$emit('input', '');
    this.change();
  }

  private mounted () {
    // this.inputWidth = this.$refs.reference.getBoundingClientRect().width
    // 配合v-clickoutside指令使用，点击popover内的元素，弹框不消失
    this.popperElm = (this.$refs.popover as any).$refs.popper;
  }
}
</script>

<style lang="stylus" scoped>
.select {
	display flex
	align-items center
}
.prompt {
	color #8c8c8c
	display block
	font-size 12px
	line-height 16px
	margin-top 4px
}
.radio {
	margin-left 28px
}
</style>
